package com.attilax.lang.net;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.reflect.ConstructorUtils;
import org.apache.commons.lang3.reflect.MethodUtils;

 

import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;

import com.attilaax.encode.EncodeX;
import com.attilax.core;
import com.attilax.lang.ParamX;
import com.attilax.ref.refx;

public class HRE_urlparamsDSLparser {

	private JWebBrowser webBrowser;

	public HRE_urlparamsDSLparser(JWebBrowser webBrowser) {
		this.webBrowser = webBrowser;
	}
	@SuppressWarnings("all")
	public void exe(String parameters) {
	
		Map m = new ParamX().urlParams2Map((String) parameters);
		List paras_li=new ArrayList();
		if(m.get("param")!=null)
			paras_li.add(m.get("param"));
		for(int i=0;i<7;i++)
		{
			String param_index = "param"+String.valueOf(i);
			if(m.get(param_index)!=null)
				paras_li.add(param_index);
			
		}
		Object[] params_objArr=paras_li.toArray();
		String meth = (String) m.get("$method");
		//$method=aaaCms.CmsImpLocalFileVer.list&
		//$callback=cate_click_callback&http_param=select++*+from+gv_material+where+material_type+%3D+6 order+by++convert%28material_description+using+gbk%29 
		//&param=6
		String classname = refx.getClassName(meth);

		String meth_name = refx.getMethodName(meth);
		String callback_fun = (String) m.get("$callback");

		Object o;

		try {
			o = ConstructorUtils.invokeConstructor(

			Class.forName(classname), null);
			Object invokeMethod_ret = MethodUtils.invokeMethod(o, meth_name,
					params_objArr);
			String ret="";
			if(  invokeMethod_ret   instanceof String)
			  ret = (String) invokeMethod_ret;
			else
				ret=core.toJsonStrO88(invokeMethod_ret);
			System.out.println("");
			ret = EncodeX.jsEncodeSingleQuoue(ret);
			String javascript = callback_fun + "('" + ret + "')";
			System.out.println("executeJavascript:"+javascript);
			webBrowser.executeJavascript(javascript);
		} catch (Throwable e) {
			String string = EncodeX.jsEncodeSingleQuoue(core.toJsonStrO88(e));
			webBrowser.executeJavascript(callback_fun + "('" + string + "')");

		}
//		RuntimeException re = new RuntimeException("calljava.refImp() err ");
//		String string = EncodeX.jsEncodeSingleQuoue(core.toJsonStrO88(re));
//		webBrowser.executeJavascript(callback_fun + "('" + string + "')");
		// return core.toJsonStrO88(new
		// RuntimeException("calljava.refImp() err ") );

	}

	private Object refImp(String meth, List li) {
		String classname = refx.getClassName(meth);

		String meth_name = refx.getMethodName(meth);

		Object o;

		try {
			o = ConstructorUtils.invokeConstructor(

			Class.forName(classname), null);
			return MethodUtils.invokeMethod(o, meth_name, li.get(0));
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {

			return core.toJsonStrO88(e);

		}

		return core
				.toJsonStrO88(new RuntimeException("calljava.refImp() err "));

	}

}
